package com.example.pictureview.widget;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.OrientationEventListener;

/**
 * Created by Administrator on 2017/7/28 0028.
 */

public class RotationObserver extends ContentObserver {
    ContentResolver mResolver;
    private final Context mContext;
    private OrientationEventListener mListener;
    private final String TAG = getClass().getSimpleName();

    public RotationObserver(Context context, OrientationEventListener listener, Handler handler) {
        super(handler);
        mContext = context;
        mResolver = mContext.getContentResolver();
        mListener = listener;

    }

    //屏幕旋转设置改变时调用
    @Override
    public void onChange(boolean selfChange) {
        Log.i(TAG, "@@onChanged:" + isScreenRotateOn());
        update();

    }

    private void update() {
        if (mListener != null) {
            if (isScreenRotateOn()) {
                mListener.enable();
            } else {
                mListener.disable();
            }
        }
    }


    private boolean isScreenRotateOn() {
        boolean autoRotateOn = (Settings.System.getInt(mContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1);
        return autoRotateOn;
    }

    public void startObserver() {

        mResolver.registerContentObserver(Settings.System
                        .getUriFor(Settings.System.ACCELEROMETER_ROTATION), false,
                this);
        update();

    }

    public void stopObserver() {
        if (mListener != null) {
            mListener.disable();
        }
        mResolver.unregisterContentObserver(this);
    }
}